#include "Socket.h"

#if defined(WIN32) || defined(_WIN32)
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <unistd.h>
#endif

#include <fcntl.h>

using namespace network;

Socket Socket::createSocket() {
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    return Socket(fd);
}

#if defined(WIN32) || defined(_WIN32)
void Socket::setNonBlock(bool on) const {
    unsigned long nonBlocking = on ? 1 : 0;
    ioctlsocket(fd_, FIONBIO, &nonBlocking);
}

void Socket::closeFd() const {
    closesocket(fd_);
}
#else

void Socket::setNonBlock(bool on) const {
    int flag = fcntl(fd_, F_GETFL);
    on ? flag |= O_NONBLOCK : flag &= ~O_NONBLOCK;
    fcntl(fd_, F_SETFL, flag);
}

void Socket::closeFd() const {
    close(fd_);
}

#endif
